/*
Copyright 2023.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package controller

import (
	"context"
	"fmt"
	"gitee.com/amoyx/devops-infras/internal/tencentcloud"
	"k8s.io/client-go/util/retry"
	"time"

	"k8s.io/apimachinery/pkg/runtime"
	ctrl "sigs.k8s.io/controller-runtime"
	"sigs.k8s.io/controller-runtime/pkg/client"
	"sigs.k8s.io/controller-runtime/pkg/log"

	appv1 "gitee.com/amoyx/devops-infras/api/v1"
)

// NacosReconciler reconciles a Nacos object
type NacosReconciler struct {
	client.Client
	Scheme *runtime.Scheme
	tencentcloud.NacosCloud
}

//+kubebuilder:rbac:groups=resources.factory.sandload.com,resources=nacos,verbs=get;list;watch;create;update;patch;delete
//+kubebuilder:rbac:groups=resources.factory.sandload.com,resources=nacos/status,verbs=get;update;patch
//+kubebuilder:rbac:groups=resources.factory.sandload.com,resources=nacos/finalizers,verbs=update

// Reconcile is part of the main kubernetes reconciliation loop which aims to
// move the current state of the cluster closer to the desired state.
// TODO(user): Modify the Reconcile function to compare the state specified by
// the Nacos object against the actual cluster state, and then
// perform operations to make the cluster state reflect the state specified by
// the user.
//
// For more details, check Reconcile and its Result here:
// - https://pkg.go.dev/sigs.k8s.io/controller-runtime@v0.15.0/pkg/reconcile
func (r *NacosReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
	logger := log.FromContext(ctx)

	var nacos appv1.Nacos
	if err := r.Get(ctx, req.NamespacedName, &nacos); err != nil {
		return ctrl.Result{}, client.IgnoreNotFound(err)
	}

	// 资源创建成功或者失败，直接返回，不执行任何逻辑
	if nacos.Status.Status == appv1.SuccessStatus || nacos.Status.Status == appv1.FailStatus {
		return ctrl.Result{}, nil
	}

	if nacos.Status.Status == appv1.CreatingStatus {
		res, err := r.QueryNacos(nacos.Status.Id)
		if err != nil {
			logger.Error(err, "ERROR: 查询nacos错误！")
			return ctrl.Result{RequeueAfter: time.Second * 10}, nil
		}

		if len(res.Response.Content) <= 0 {
			logger.Info(fmt.Sprintf("WARN: 没有查到该%s nacos实例，检查是否创建成功？", nacos.Status.Id))
			return ctrl.Result{RequeueAfter: time.Second * 10}, nil
		}

		if *res.Response.Content[0].Status != "running" {
			logger.Info("INFO: nacos实例正在创建中， 还未完全创建完毕！")
			return ctrl.Result{RequeueAfter: time.Second * 10}, nil
		}

		if nacos.Status.Status == appv1.CreatingStatus && nacos.Status.ExternalStatus != appv1.CreatingStatus {
			if err = r.UpdateInternetAccess(nacos.Status.Id, true); err != nil {
				logger.Error(err, "ERROR: 开启nacos公网地址失败")
				return ctrl.Result{RequeueAfter: 15 * time.Second}, nil

			}

			if err = retry.RetryOnConflict(retry.DefaultRetry, func() error {
				var reNacos appv1.Nacos
				if err = r.Get(ctx, req.NamespacedName, &reNacos); err != nil {
					logger.Error(err, "获取nacos实例错误")
					return err
				}

				reNacos.Status.ExternalStatus = appv1.CreatingStatus
				if err = r.Status().Update(ctx, &reNacos); err != nil {
					logger.Error(err, "更新创建nacos实例状态失败")
				}
				return nil
			}); err != nil {
				logger.Error(err, "更新创建nacos实例状态失败")
			}
			return ctrl.Result{}, nil
		}

		queryAddr, err := r.QueryAccessAddress(nacos.Status.Id)
		if err != nil {
			logger.Error(err, "查询nacos公网地址失败，稍后再重试。。。")
			return ctrl.Result{RequeueAfter: 10 * time.Second}, nil
		}

		if len(*queryAddr.Response.InternetAddress) == 0 {
			logger.Info("nacos外网地址为空，等待重试。。")
			return ctrl.Result{RequeueAfter: time.Second * 15}, nil
		}

		if err = retry.RetryOnConflict(retry.DefaultRetry, func() error {
			var reNacos appv1.Nacos
			if err := r.Get(ctx, req.NamespacedName, &reNacos); err != nil {
				return err
			}

			reNacos.Status.InternetAddress = *queryAddr.Response.InternetAddress
			reNacos.Status.IntranetAddress = *queryAddr.Response.IntranetAddress
			reNacos.Status.Status = appv1.SuccessStatus
			if err = r.Status().Update(ctx, &reNacos); err != nil {
				logger.Error(err, "更新nacos状态失败")
				return err
			}
			return nil
		}); err != nil {
			logger.Error(err, "更新nacos状态失败")
			return ctrl.Result{}, nil
		}
		logger.Info("创建nacos成功")
		return ctrl.Result{}, nil
	}

	var tmpNacos appv1.Nacos
	if err := r.Get(ctx, req.NamespacedName, &tmpNacos); err != nil {
		return ctrl.Result{}, client.IgnoreNotFound(err)
	}

	if len(tmpNacos.Status.Status) != 0 {
		return ctrl.Result{}, nil
	}

	tmpNacos.Status.Status = appv1.CreatingStatus
	if err := r.Status().Update(ctx, &tmpNacos); err != nil {
		logger.Error(err, "更新nacos状态失败")
		return ctrl.Result{}, nil
	}

	logger.Info("===============  开始创建nacos ===================")
	createRes, err := r.CreateNacos(&nacos)
	s := appv1.CreatingStatus
	var id string
	if err != nil {
		logger.Error(err, "创建nacos失败")
		s = appv1.FailStatus
	} else {
		id = *createRes.Response.InstanceId
	}

	if err = retry.RetryOnConflict(retry.DefaultRetry, func() error {
		var newNacos appv1.Nacos
		if err = r.Get(ctx, req.NamespacedName, &newNacos); err != nil {
			return err
		}
		newNacos.Status.Status = s
		newNacos.Status.Id = id
		if err = r.Status().Update(ctx, &newNacos); err != nil {
			logger.Error(err, "更新nacos状态失败")
			return err
		}
		return nil
	}); err != nil {
		logger.Error(err, "重试创建nacos失败")
		return ctrl.Result{}, nil
	}
	return ctrl.Result{RequeueAfter: time.Second * 10}, nil
}

// SetupWithManager sets up the controller with the Manager.
func (r *NacosReconciler) SetupWithManager(mgr ctrl.Manager) error {
	return ctrl.NewControllerManagedBy(mgr).
		For(&appv1.Nacos{}).
		Complete(r)
}
